//
//  AssistiveTouch.m
//  Common
//
//  Created by shiqing guo on 2018/7/31.
//  Copyright © 2018年 www.bitkinetic.com. All rights reserved.
//

#import "AssistiveTouch.h"
#import "Macro.h"
#import "UIView+DDAddition.h"

#define kAssistiveTouchIMG    [UIImage imageNamed:@"trip_plus60"]
#define kPrompt_DismisTime    0.2
#define kAlpha                0.5
#define kAllowance            30.0f

@interface AssistiveTouch ()
@property (nonatomic, strong) UIButton *btnTouch;
@end

@implementation AssistiveTouch

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.frame = frame;
        
        self.backgroundColor = [UIColor clearColor];
        self.windowLevel = UIWindowLevelAlert + 1;
        [self makeKeyAndVisible];
        
        [self addSubview:self.btnTouch];
        
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(changePostion:)];
        [self.btnTouch addGestureRecognizer:pan];
    }
    return self;
}

#pragma mark - Lazy
- (UIButton *)btnTouch
{
    if (!_btnTouch) {
        _btnTouch = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btnTouch setBackgroundImage:kAssistiveTouchIMG forState:UIControlStateNormal];
        [_btnTouch setBackgroundImage:kAssistiveTouchIMG forState:UIControlStateDisabled];
        [_btnTouch setBackgroundImage:kAssistiveTouchIMG forState:UIControlStateHighlighted];
        _btnTouch.frame = CGRectMake(0, 0, self.width, self.height);
        [_btnTouch addTarget:self action:@selector(assistiveTouchAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnTouch;
}

- (void)setImageName:(NSString *)imageName
{
    UIImage *image = [UIImage imageNamed:imageName];
    [self.btnTouch setBackgroundImage:image forState:UIControlStateNormal];
    [self.btnTouch setBackgroundImage:image forState:UIControlStateDisabled];
    [self.btnTouch setBackgroundImage:image forState:UIControlStateHighlighted];
    [self setNeedsDisplay];
}

#pragma mark - private action
- (void)assistiveTouchAction:(id)sender
{
    WEAKSELF
    [UIView animateWithDuration:kPrompt_DismisTime animations:^{
        weakSelf.alpha = 0;
    } completion:^(BOOL finished) {
        [kWindow endEditing:YES];
    }];
    if (self.clickBlock) self.clickBlock();
}


- (void)changePostion:(UIPanGestureRecognizer *)pan
{
    CGPoint point = [pan translationInView:self];
    
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    CGFloat height = [UIScreen mainScreen].bounds.size.height;
    
    CGRect originalFrame = self.frame;
    if (originalFrame.origin.x >= 0 && originalFrame.origin.x+originalFrame.size.width <= width) {
        originalFrame.origin.x += point.x;
    }
    if (originalFrame.origin.y >= 0 && originalFrame.origin.y+originalFrame.size.height <= height) {
        originalFrame.origin.y += point.y;
    }
    self.frame = originalFrame;
    [pan setTranslation:CGPointZero inView:self];
    
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:
        {
            [self beginPoint];
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            [self changePoint];
        }
            break;
        case UIGestureRecognizerStateEnded:
        {
            [self endPoint];
        }
            break;
        case UIGestureRecognizerStateCancelled:
        {
            [self endPoint];
        }
            break;
            
        default:
            break;
    }
    
}
- (void)beginPoint {
    
    self.btnTouch.enabled = NO;
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [UIView animateWithDuration:kPrompt_DismisTime animations:^{
        self.alpha = 1.0;
    }];
}
- (void)changePoint {
    
    BOOL isOver = NO;
    
    CGRect frame = self.frame;
    
    if (frame.origin.x < 0) {
        frame.origin.x = 0;
        isOver = YES;
    } else if (frame.origin.x+frame.size.width > UI_SCREEN_WIDTH) {
        frame.origin.x = UI_SCREEN_WIDTH - frame.size.width;
        isOver = YES;
    }
    
    if (frame.origin.y < NavBar_Height) {
        frame.origin.y = NavBar_Height;
        isOver = YES;
    } else if (frame.origin.y+frame.size.height > UI_CONTENT_MAXY) {
        frame.origin.y = UI_CONTENT_MAXY - frame.size.height;
        isOver = YES;
    }
    if (isOver) {
        [UIView animateWithDuration:kPrompt_DismisTime animations:^{
            self.frame = frame;
        }];
    }
    self.btnTouch.enabled = YES;
}


- (void)endPoint {
    
    if (self.left <= UI_SCREEN_WIDTH / 2 - self.width/2) {
        
        if (self.top >= UI_SCREEN_HEIGHT - self.height - kAllowance) {
            self.top = UI_SCREEN_HEIGHT - self.height;
        }else
        {
            if (self.top <= kAllowance) {
                self.top = 0;
            }else
            {
                self.left = 0;
            }
        }
        
    }else
    {
        if (self.top >= UI_SCREEN_HEIGHT - self.height - kAllowance) {
            self.top = UI_SCREEN_HEIGHT - self.height;
        }else
        {
            if (self.top <= kAllowance) {
                self.top = 0;
            }else
            {
                self.left = UI_SCREEN_WIDTH - self.width;
            }
        }
    }
    
    self.btnTouch.enabled = YES;
//    [self performSelector:@selector(setAlpha) withObject:nil afterDelay:3];
}


- (void)setAlpha {
    [UIView animateWithDuration:kPrompt_DismisTime animations:^{
        self.alpha = kAlpha;
    }];
}

- (void)setShow {
    [UIView animateWithDuration:kPrompt_DismisTime animations:^{
        self.alpha = 1.0;
    }];
}

- (void)setHide {
    [UIView animateWithDuration:kPrompt_DismisTime animations:^{
        self.alpha = 0;
    }];
}


@end
